<template>
    <div class="PersonalSetting">
      <el-row>
        <el-col :offset="1" :span="22">
          <div class="grid-content bg-purple-dark">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <el-button class="button" type="text" @click="handleBack"><i class="el-icon-arrow-left" />返回</el-button>
                  <span>个人设置</span>
                  <div></div>
                </div>
              </template>
              <el-tabs :tab-position="tabPosition">
                <el-tab-pane label="基本设置">
                  <div class="set-title">
                    <span>基本设置</span>
                  </div>
                  <div class="set-info">
                    <div class="form-info">
                      <el-form ref="settingForm" :model="settingForm" :rules="rules" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="邮箱" prop="email">
                          <el-input v-model="settingForm.email" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="sex">
                          <el-radio-group v-model="settingForm.sex" size="small">
                          <el-radio-button label="man">男</el-radio-button>
                          <el-radio-button label="woman">女</el-radio-button>
                        </el-radio-group>
                        </el-form-item>
                        <el-form-item label="个人简介" prop="individualResume">
                          <el-input v-model="settingForm.individualResume" type="textarea" placeholder="个人简介" maxlength="120"></el-input>
                        </el-form-item>
  
                        <el-form-item label="联系电话" prop="phoneNumber">
                          <el-input v-model="settingForm.phoneNumber" placeholder="请输入11位大陆手机号码"></el-input>
                        </el-form-item>
  
                        <el-form-item>
                          <el-button type="primary" :loading="updateLoading" @click="submitForm()">更新基本信息</el-button>
                          <el-button @click="resetForm()">重置</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                    <div class="avatar">
                      <div class="preview">
                        <span>头像</span>
                        <img v-if="showImg()" :src="showImg()" onerror="this.src='user.jpg';this.onerror=null" />
                      </div>
                      <el-upload
                        class="avatar-uploader"
                        action="#"
                        :auto-upload="false"
                        :http-request="uploadFile"
                        limit="1"
                        ref="upload"
                        :show-file-list="true"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >
                        <el-button style="margin-left: 10px" size="small" type="success"><i class="el-icon-upload"></i>更换头像</el-button>
                      </el-upload>
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="安全设置">
                  <div class="set-title">
                    <span>安全设置</span>
                  </div>
                  <div class="secure-item">
                    <div class="secure-info">
                      <span class="secure-key">账户密码</span>
                      <span class="secure-value">当前密码强度：强</span>
                    </div>
                    <div class="opera-btn"><span>修改</span></div>
                  </div>
                  <div class="secure-item">
                    <div class="secure-info">
                      <span class="secure-key">密保手机</span>
                      <span class="secure-value">已绑定手机：138****2234</span>
                    </div>
                    <div class="opera-btn"><span>修改</span></div>
                  </div>
                  <div class="secure-item">
                    <div class="secure-info">
                      <span class="secure-key">绑定邮箱</span>
                      <span class="secure-value">已绑定邮箱：geek****@outlook.com</span>
                    </div>
                    <div class="opera-btn"><span>修改</span></div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-card></div
        ></el-col>
      </el-row>
    </div>
  </template>

<script>
import Cookie from 'js-cookie'
export default {
    data(){
        return{
            name: 'PersonalSetting',
            img:null,
            settingForm:{
                email: '',
                sex: '',
                individualResume: '',
                phoneNumber: ''
            },
            rules:{
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                sex: { required: true, message: '请选择性别', trigger: ['blur', 'change'] },
                individualResume: { required: true, message: '请输入个人简介', trigger: ['blur', 'change'] },
                phoneNumber: [{ required: true, message: '请输入手机号码', trigger: ['blur', 'change'] },
                        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }]
            }
        }
     },
     methods:{
       convertToImage(binaryString) {
          const byteCharacters = atob(binaryString); // 将base64编码的二进制字符串解码为原始字节流
          const byteArrays = [];
            for (let offset = 0; offset < byteCharacters.length; offset += 512) {
                const slice = byteCharacters.slice(offset, offset + 512);
                const byteNumbers = new Array(slice.length);
                for (let i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                  }
              const byteArray = new Uint8Array(byteNumbers);
              byteArrays.push(byteArray);
            }
          const blob = new Blob(byteArrays, { type: 'image/jpeg' }); // 根据实际情况设置MIME类型
          return URL.createObjectURL(blob); // 生成URL
        },
        showImg(){
          return this.convertToImage(this.img)
        },
        getUserInfo(){
          let token=Cookie.get('token')
          if(token===null||token===undefined||''===token){
            this.$message({
                type: 'error',
                message: "获取相关信息，请先登录！"
            });
            return
          }
          this.$axios.get('/getUserInfo').then(({data}) => {// 请求成功，返回
                if(data.code===200){
                    this.settingForm.email=data.data.user.email
                    this.settingForm.sex=data.data.user.sex
                    this.settingForm.individualResume=data.data.user.individualResume
                    this.settingForm.phoneNumber=data.data.user.phoneNumber
                    this.img=data.data.user.img
                    this.$message({
                        type: 'success',
                        message: data.data.message
                    });
                }else{
                    this.$message({
                        type: 'error',
                        message: data.data.message
                    });
                }
            })
            .catch((err) => {// 请求失败
                console.log(err);
            });
        },
        uploadFile(param){
            this.img=param.file
            console.log(this.img)
        },
        handleBack(){
            this.$router.go(-1)
        },
        submitForm(){
          let token=Cookie.get('token')
          if(token===null||token===undefined||''===token){
            this.$message({
                type: 'error',
                message: "获取相关信息，请先登录！"
            });
            return
          }
            this.$refs.settingForm.validate((valid) => {
                if(valid){
                  this.$refs.upload.submit()
                  const formDatas = new FormData();
                  formDatas.append("email",this.settingForm.email)
                  formDatas.append("sex",this.settingForm.sex)
                  formDatas.append("individualResume",this.settingForm.individualResume)
                  formDatas.append("phoneNumber",this.settingForm.phoneNumber)
                  formDatas.append('file',this.img)
                  this.$axios.post('/updateUserInfo',formDatas,{headers: {'Content-Type': 'multipart/form-data'}})
                        .then(({data}) => {// 请求成功，返回
                            if(data.code===200){
                                this.$message({
                                    type: 'success',
                                    message: data.data.message
                                });
                                this.getUserInfo()
                            }else{
                                this.$message({
                                    type: 'error',
                                    message: data.data.message
                                });
                            }
                        })
                        .catch((err) => {// 请求失败
                            console.log(err);
                        });
                    
                }else{
                    this.$message({
                        type: 'error',
                        message: '更新失败!'
                    });
                }
             });
        },
        resetForm(){
            this.$refs.settingForm.resetFields()
            this.$refs.upload.clearFiles()
            this.$message({
                type: 'success',
                message: '重置成功!'
            });
        }
     },
     computed:{
        // getImg(){
        //     return URL.createObjectURL(this.img)
        // }
     },
     mounted(){
        this.getUserInfo()
     }

    
}
</script>

<style lang="less" scoped>
.PersonalSetting{
  height: 600px;
    margin-top:20px;
    .demo-ruleForm{
        text-align :left;
    }
    .set-title{
      text-align :left;
    }
    .secure-item{
      width:100%;
      padding:20px;
      border-bottom:1px solid #f0f0f0;
      display :flex;
      flex-direction:row;
      justify-content :space-between;
      align-items :center;
      .secure-info{
         display :flex;
      flex-direction:column;
      justify-content :flex-start;
      align-items :flex-start;
        .secure-key{
          margin-bottom: 4px;
          color: rgba(0,0,0,.85);
          font-size: 14px;
          line-height: 1.6;
        }
        .secure-value{
          color: rgba(0,0,0,.45);
          font-size: 14px;
          line-height: 1.6;
        }
      }
      .opera-btn{
        color:#1890ff;
        cursor:pointer;
        margin-right: 50px;
      }
    }
    .set-info{
      display :flex;
      flex-direction :row;
      justify-content :space-around;
      align-items :flex-start;
      .form-info{

      }
      .avatar{
        display :flex;
        flex-direction:row;
        justify-content:flex-start;
        align-items :flex-end;
        .preview{
           display :flex;
        flex-direction:column;
        justify-content:flex-start;
        align-items :flex-start;
        margin-right:20px;
         img{
            width:174px;
          height:174px;
          border-radius:50%;
         }
        }

          .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
          }
          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
          }
          .avatar {
            width: 178px;
            height: 178px;
            display: block;
          }
      }
    }
    .info{
        text-align: left;
    padding-left: 20px;
    margin-bottom: 20px;
    font-size: 12px;
    }
     .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .box-card {
    width:100%;
  }
}
</style>